########################################################################
# dialogs.py - Utility dialogs used all over in the program.  Basic
#	things like message boxes, input boxes, etc.  The core functionality
#	is in wxPython; this module just wraps them in a way that makes that
#	funtionality easy to use within this program.
#
# Created 2006.04.29 by Warren Young
#
# Copyright (c) 2006 by Pixel Corps.  This program may be used under
# the terms of the X11 license, a copy of which should have accompanied
# this program, in the LICENSE file.
########################################################################

import gui, localparms

import wx

import thread


#### class EmulateSynchronous ##########################################
# This class uses mutexes to emulate a synchronous call to a function
# running in the GUI thread from another thread.  The calling thread
# blocks until the GUI function returns.
#
# This is necessary because wxPython doesn't play well with multiple
# threads, so all GUI code must run in one thread.  See p.539 in
# _wxPython in Action_ for more on this topic.

class EmulateSynchronous:
	def __init__(self, arg):
		self.mutex = thread.allocate_lock()
		self.mutex.acquire()
		wx.CallAfter(self.Callback, arg)
		self.mutex.acquire()

	def CallComplete(self):
		self.mutex.release()


#### class MessageBox ##################################################
# The object converts the constructor's arguments to strings, tacks them
# together into a single string, and displays that in a window with an
# OK button.

class MessageBox(EmulateSynchronous):
	def __init__(self, *msg):
		EmulateSynchronous.__init__(self, msg)

	def Callback(self, args):
		s = ''
		for a in args:
			s += str(a)

		dlg = wx.MessageDialog(gui.GetMainFrame(), s,
				localparms.parms.programName, wx.OK | wx.CENTRE)
		dlg.ShowModal()

		self.CallComplete()


#### class PasswordRequest #############################################
# Get a password from the user.

class PasswordRequest(EmulateSynchronous):
	def __init__(self, prompt):
		EmulateSynchronous.__init__(self, prompt)

	def Callback(self, prompt):
		dlg = wx.PasswordEntryDialog(gui.GetMainFrame(), prompt)
		dlg.CenterOnScreen()
		dlg.Raise()
		if dlg.ShowModal() == wx.ID_OK:
			self.password = dlg.GetValue()
		else:
			self.password = None

		self.CallComplete()


#### class YesNoQuestion ###############################################
# Ask the user a yes/no question

class YesNoQuestion(EmulateSynchronous):
	def __init__(self, *args):
		EmulateSynchronous.__init__(self, args)

	def Callback(self, args):
		question = ''
		for a in args:
			question += str(a)

		dlg = wx.MessageDialog(gui.GetMainFrame(), question,
				localparms.parms.programName,
				wx.YES_NO | wx.NO_DEFAULT | wx.CENTRE)
		self.answer = (dlg.ShowModal() == wx.ID_YES)

		self.CallComplete()
